package svc.elib.util;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class Distribution {

	public class MutableInt {
		private int freq;
		public MutableInt(int freq) { this.freq = freq; }
		public void inc() { ++freq; }
		public void set(int newVal) { freq = newVal; }
		public int get() { return freq; }
		public void inc(int delta) {
			freq += delta;
		}
	}
	
	private TreeMap<Integer, MutableInt> distr =
		new TreeMap<Integer, MutableInt>();
	
	public class DistrEntry {
		int freq;
		int val;
		public DistrEntry(int val, int freq) {
			this.val = val;
			this.freq = freq;
		}
	}
	
	public Distribution(LinkedList<Integer> data) {
		for (int i = 0; i < data.size(); i++) {
			int val = data.get(i);
			MutableInt f = distr.get(val);
			if (f == null) {
				f = new MutableInt(1);
				distr.put(val, f);
			} else {
				f.inc();
			}
		}
	}
	
	public void printDistr() {
		Set<Entry<Integer, MutableInt>> es = distr.entrySet();
		Iterator<Entry<Integer, MutableInt>> it = es.iterator();
		while (it.hasNext()) {
			Entry<Integer, MutableInt> e = it.next();
			System.out.println(e.getKey() + ", " + e.getValue().get());
		}
	}
	
	public void printComplementaryCumulative() {
		LinkedList<Entry<Integer, MutableInt>> d = 
			new LinkedList<Entry<Integer, MutableInt>>();
		
		Set<Entry<Integer, MutableInt>> es = distr.entrySet();
		Iterator<Entry<Integer, MutableInt>> it = es.iterator();
		while (it.hasNext()) {
			Entry<Integer, MutableInt> e = it.next();
			d.addLast(e);
		}
		
		double sum = 0.0;
		for (Entry<Integer, MutableInt> e : d) {
			sum += e.getValue().get();
		}
		
		for (int i = d.size() - 2; i >= 0; i--) {
			Entry<Integer, MutableInt> current = d.get(i);
			Entry<Integer, MutableInt> next = d.get(i + 1);
			current.getValue().inc(next.getValue().get());
		}
		
		for (Entry<Integer, MutableInt> e : d) {
			int x = e.getKey();
			double y = (double) e.getValue().get() / sum;
			System.out.println(x + ", " + y);
		}
	}
}
